//bedit.cpp
#include <QHBoxLayout>
#include <QTextEdit>
#include "bedit.h"

BadgerEditor::BadgerEditor( )
{
	lastNumLines = 0;
	QHBoxLayout* hb = new QHBoxLayout( this );
	ln = new QTextEdit;
	ln->setLineWrapMode( QTextEdit::NoWrap );
	ln->setReadOnly ( true );
	ln->setMinimumWidth ( ln->document()->idealWidth() );
	ln->setMaximumWidth ( ln->document()->idealWidth() );
	ln->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
	ln->setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
	ln->setAlignment ( Qt::AlignLeft );
	ln->setFrameStyle( QFrame::Panel | QFrame::Sunken );

	editor = new srchiliteqt::TextEditHighlighted;
	editor->setLineWrapMode( QTextEdit::NoWrap );
	editor->setFrameStyle( QFrame::Panel | QFrame::Sunken );

	hb->addWidget( ln );
	hb->addWidget( editor );

	setLayout( hb );
	connect ( (QObject*)editor->verticalScrollBar(), SIGNAL ( valueChanged ( int ) ), (QObject*)ln->verticalScrollBar(), SLOT ( setValue ( int ) ) );
	connect ( editor, SIGNAL ( textChanged() ), this, SLOT ( updateLN() ) );
	setFocusProxy ( editor );
	updateLN();

}
void BadgerEditor::loadFile( QString& ifile )
{

	loadedFile = ifile;
	editor->loadFile( ifile );
	updateLN();

}

void BadgerEditor::updateLN()
{
	if ( lastNumLines == 0 )
	{
		ln->append ( QString ( "%1" ).arg ( 1 ) );
		lastNumLines++;
		return;
	}

	if ( lastNumLines < editor->document()->blockCount() )
	{
		int lns = ++lastNumLines;
		lastNumLines = editor->document()->blockCount();

		while ( lns <= lastNumLines )
		{
			ln->append ( QString ( "%1" ).arg ( lns ) );
			lns++;
		};
		return;
	}

	if ( lastNumLines > editor->document()->blockCount() )
	{
		int lns = lastNumLines;
		QString newText = ln->toPlainText();

		while ( lns > editor->document()->blockCount() )
		{
			newText.replace ( QString ( "%1\n" ).arg ( lns ), QString() );
			newText.replace ( QString ( "%1" ).arg ( lns ), QString() );
			--lns;
		}

		lastNumLines = editor->document()->blockCount();
		ln->setText ( newText );
	}

	ln->setMinimumWidth ( ln->document()->idealWidth() );
	ln->setMaximumWidth ( ln->document()->idealWidth() );

};

